//
//  WeChatHelper.m
//  xiximiren-ios
//
//  Created by Zyark on 2017/9/21.
//  Copyright © 2017年 egret. All rights reserved.
//

#import "WeChatHelper.h"

#import "ZYWeChatConfig.h"
//#import "WXApiRequestHandler.h"
#import "WXApiManager.h"
#import "WechatAuthSDK.h"
#import "AFNetWorking.h"
#import "AFNetworkActivityIndicatorManager.h"

@implementation WeChatHelper
-(void)weChatLoginWithController:(UIViewController *)vc{
//    NSString *accessToken = [[NSUserDefaults standardUserDefaults] objectForKey:WX_ACCESS_TOKEN];
//    NSString *openID = [[NSUserDefaults standardUserDefaults] objectForKey:WX_OPEN_ID];
//    // 如果已经请求过微信授权登录，那么考虑用已经得到的access_token
//    if (accessToken && openID) {
//        AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
//        NSString *refreshToken = [[NSUserDefaults standardUserDefaults] objectForKey:WX_REFRESH_TOKEN];
//        NSString *refreshUrlStr = [NSString stringWithFormat:@"%@/oauth2/refresh_token?appid=%@&grant_type=refresh_token&refresh_token=%@", WX_BASE_URL, WX_APP_ID, refreshToken];
//        manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/plain"];
//        [manager GET:refreshUrlStr parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
//            NSLog(@"请求reAccess的response = %@", responseObject);
//            NSDictionary *refreshDict = [NSDictionary dictionaryWithDictionary:responseObject];
//            NSString *reAccessToken = [refreshDict objectForKey:WX_ACCESS_TOKEN];
//            // 如果reAccessToken为空,说明reAccessToken也过期了,反之则没有过期
//            if (reAccessToken) {
//                // 更新access_token、refresh_token、open_id
////                NSString *unionid = [refreshDict objectForKey:WX_UNION_ID];
//                [[NSUserDefaults standardUserDefaults] setObject:reAccessToken forKey:WX_ACCESS_TOKEN];
//                [[NSUserDefaults standardUserDefaults] setObject:[refreshDict objectForKey:WX_OPEN_ID] forKey:WX_OPEN_ID];
////                [[NSUserDefaults standardUserDefaults] setObject:unionid forKey:WX_UNION_ID];
//                [[NSUserDefaults standardUserDefaults] setObject:[refreshDict objectForKey:WX_REFRESH_TOKEN] forKey:WX_REFRESH_TOKEN];
//                [[NSUserDefaults standardUserDefaults] synchronize];
//                // 当存在reAccessToken不为空时直接执行AppDelegate中的wechatLoginByRequestForUserInfo方法
//                //                !self.requestForUserInfoBlock ? : self.requestForUserInfoBlock();
//                [[EgretRuntime getInstance] callEgretInterface:@"successWxLogin" value:unionid];
//            }
//            else {
//                [self doWeChatLogin:vc];
//            }
//        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
//            NSLog(@"用refresh_token来更新accessToken时出错 = %@", error);
//            [[EgretRuntime getInstance] callEgretInterface:@"errorWxLogin" value:@""];
//        }];
//    }
//    else {
        [self doWeChatLogin:vc];
//    }
}

- (void)doWeChatLogin:(UIViewController *)vc {
    if ([WXApi isWXAppInstalled]) {
        SendAuthReq *req = [[SendAuthReq alloc] init];
        req.scope = @"snsapi_userinfo";
        req.state = @"123";
        [WXApi sendReq:req];
    }
    else {
        [self setupAlertController:vc];
    }
}

- (void)setupAlertController:(UIViewController *)vc {
    
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"温馨提示" message:@"请先安装微信客户端" preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *actionConfirm = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil];
    [alert addAction:actionConfirm];
    [vc presentViewController:alert animated:YES completion:nil];
}

-(void)getAccessTokenWithCode:(NSString *)code{
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/plain"];
    NSString *accessUrlStr = [NSString stringWithFormat:@"%@/oauth2/access_token?appid=%@&secret=%@&code=%@&grant_type=authorization_code", WX_BASE_URL, WX_APP_ID, WX_APP_SECRET,code];
    [manager GET:accessUrlStr parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"请求access的response = %@", responseObject);
        NSDictionary *accessDict = [NSDictionary dictionaryWithDictionary:responseObject];
        NSString *accessToken = [accessDict objectForKey:WX_ACCESS_TOKEN];
        NSString *openID = [accessDict objectForKey:WX_OPEN_ID];
        NSString *unionid = [accessDict objectForKey:WX_UNION_ID];
        NSString *refreshToken = [accessDict objectForKey:WX_REFRESH_TOKEN];
        // 本地持久化，以便access_token的使用、刷新或者持续
        if (accessToken && ![accessToken isEqualToString:@""] && openID && ![openID isEqualToString:@""]) {
            [[NSUserDefaults standardUserDefaults] setObject:accessToken forKey:WX_ACCESS_TOKEN];
            [[NSUserDefaults standardUserDefaults] setObject:openID forKey:WX_OPEN_ID];
            [[NSUserDefaults standardUserDefaults] setObject:unionid forKey:WX_UNION_ID];
            [[NSUserDefaults standardUserDefaults] setObject:refreshToken forKey:WX_REFRESH_TOKEN];
            [[NSUserDefaults standardUserDefaults] synchronize]; // 命令直接同步到文件里，来避免数据的丢失
        }

    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"获取access_token时出错 = %@", error);

    }];
}

-(void)shareImage:(NSData *)imageData{
    WXMediaMessage *message = [WXMediaMessage message];
    UIImage *image = [UIImage imageWithData:imageData];
    [message setThumbImage:[self compressImage:image toTargetWidth:image.size.width * 0.5]];
    WXImageObject *imageObject = [WXImageObject object];
    imageObject.imageData = imageData;
    message.mediaObject = imageObject;
    
    SendMessageToWXReq *req = [[SendMessageToWXReq alloc] init];
    req.bText = NO;
    req.message = message;
    req.scene = WXSceneSession;
    [WXApi sendReq:req];
}

/**
 压缩图片
 **/
- (UIImage *)compressImage:(UIImage *)sourceImage toTargetWidth:(CGFloat)targetWidth {
    CGSize imageSize = sourceImage.size;
    
    CGFloat width = imageSize.width;
    CGFloat height = imageSize.height;
    
    CGFloat targetHeight = (targetWidth / width) * height;
    
    UIGraphicsBeginImageContext(CGSizeMake(targetWidth, targetHeight));
    [sourceImage drawInRect:CGRectMake(0, 0, targetWidth, targetHeight)];
    
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    return newImage;
}

-(void)shareLink:(NSString *)link title:(NSString *)title description:(NSString *)description scene:(NSInteger)scene{
    //创建发送对象实例
    SendMessageToWXReq *sendReq = [[SendMessageToWXReq alloc] init];
    sendReq.bText = NO;//不使用文本信息
    if(scene == 0){
        sendReq.scene = WXSceneSession;
    }else if(scene == 1){
        sendReq.scene = WXSceneTimeline;
    }else{
        sendReq.scene = WXSceneFavorite;
    }
    //0 = 好友列表 1 = 朋友圈 2 = 收藏
    
    //创建分享内容对象
    WXMediaMessage *urlMessage = [WXMediaMessage message];
    urlMessage.title = title;//分享标题
    urlMessage.description = description;//分享描述
    [urlMessage setThumbImage:[UIImage imageNamed:@"AppIcon60x60"]];//分享图片,使用SDK的setThumbImage方法可压缩图片大小
    
    //创建多媒体对象
    WXWebpageObject *webObj = [WXWebpageObject object];
    webObj.webpageUrl = link;//分享链接
    
    //完成发送对象实例
    urlMessage.mediaObject = webObj;
    sendReq.message = urlMessage;
    
    //发送分享信息
    [WXApi sendReq:sendReq];

}

-(void)shareText:(NSString *)text{
    SendMessageToWXReq *sendReq = [[SendMessageToWXReq alloc] init];
    sendReq.bText = YES;
    sendReq.scene = WXSceneSession;//0 = 好友列表 1 = 朋友圈 2 = 收藏
    sendReq.text = text;
    [WXApi sendReq:sendReq];
}

@end
